import { getElement, Portal } from "magic-ui-react";
import { ReactNode } from "react";
import { createRoot } from "react-dom/client";

export type AppContextMenuOpenPropsType = {
  e: React.MouseEvent<HTMLDivElement, MouseEvent>,
  content: (
    appContextMenuClose: () => void
  ) => ReactNode
}

type AppWindow = {
  searchSuggestion?: (res: any) => void
} & Window

let appContextMenu: [
  Element, {
    destory: () => void
  }
] | null = null

/**
 * 关闭自定义右键菜单
 */
const appContextMenuClose = () => {
  if (appContextMenu) {
    const [
      _appContextMenuElement,
      {
        destory
      },
    ] = appContextMenu
    destory()
    appContextMenu = null
  }
}

document.addEventListener('click', () => {
  appContextMenuClose()
})


/**
 * 打开鼠标右键
 * @param e 
 * @param content 
 */
export const appContextMenuOpen = (
  e: AppContextMenuOpenPropsType['e'],
  content: AppContextMenuOpenPropsType['content']
) => {

  if (appContextMenu) {
    appContextMenuClose()
  }
  appContextMenu = getElement('appContextMenuElement', {
    attributes: [
      {
        qualifiedName: 'style',
        value: `position: absolute;top: ${e.clientY}px;left: ${e.clientX}px`
      },
    ]
  })
  const [
    appContextMenuElement
  ] = appContextMenu

  let root = createRoot(appContextMenuElement!);

  root.render(
    <Portal visible={true} container={appContextMenuElement!}>
      {content(appContextMenuClose)}
    </Portal>
  );
}

/**
 * Jsonp跨域请求关键词联想
 * @param value 
 * @param configs 
 */
export const searchSuggestionJsonp = (
  value: string,
  configs?: {
    callback?: (res: any) => void,
  }
) => {
  const res = document.querySelector('#scriptSearch')
  if (res) {
    document.body.removeChild(res)
  }
  const script = document.createElement('script')
  script.id = 'scriptSearch';
  (window as AppWindow).searchSuggestion = (res) => {
    configs?.callback?.(res.s)
  }
  script.src = `https://suggestion.baidu.com/su?q=10&ie=UTF-8&cb=window.searchSuggestion&wd=${value}`
  document.body.appendChild(script)
}

